<template>
	<view class="">
		<navBar title="病害維修" @goBack="uni.navigateBack()"></navBar>
		<disease-info-vue :showInfo="diseaseFormInfo" ref="diseaseInfoVueRef" :disabled="showButton"></disease-info-vue>
		<template>
			<view v-for="(item, index) in engineeringList" :key="index">
				<view class="label-txt">
					<view class="left">工程量</view>
					<view class="right" @click="deleteItem(index)" v-if="index != 0 && showButton">刪除</view>
				</view>
				<template v-if="diseaseFormInfo.orderType === 'WO'">
						<view class="label" style="padding-left:40rpx;padding-top: 30rpx;">工程項{{ index + 1}}</view>
						<view class="label-item" @click="goWoItem(index)">
							<view class="title-txt">{{ item.coding && item.projectItem ? `${item.coding}:${item.projectItem}` : '' }}</view>
							<u-icon v-if="showButton" name="arrow-down" color="#a7aebd" size="16"></u-icon>
						</view>
						<view class="label-tips" v-if="item.code">{{ item.code || '' }}</view>
					<view v-if="item.children && item.children.length && item.coding !== 'J'">
						<view v-for="(item1, index1) in item.children" :key="index1" class="input-box">
							<view v-for="(child, idx) in item1" :key="idx" :class="{'m40':idx === 1}">
								<view>{{ child.coding }}:</view>
								<u--input :placeholder="child.projectItem" border="surround" v-model="child.value"
									:adjustPosition="false" inputAlign="left" style="width: 80%;" type="digit" :disabled="!showButton"></u--input>
							</view>
						</view>
					</view>
					<view style="padding: 0 32rpx;" v-if="item.coding === 'J'">
						<u-input :adjustPosition="false" placeholder="請輸入描述" border="surround" v-model="item.value"  inputAlign="left" :disabled="!showButton"></u-input>
					</view>
				</template>
				
				<template v-else>
					<view class="form-item">
						<view class="label">工程項{{ index + 1}}</view>
						<view class="form-content">
							<view class="form-text">
								<u-input placeholder="请输入" :adjustPosition="false" border="none" v-model="item.value"  inputAlign="left" :disabled="!showButton"></u-input>
							</view>
						</view>
					</view>
				</template>
				<view class="picture_box_1" v-if="true">
					<view class="txt">維修照片</view>
						<u-upload v-if="showButton"  :fileList="engineeringList[index].fileListImg" @afterRead="afterRead($event, index)"
							@delete="deletePic($event, index)" name="Img" multiple :maxCount="9"
							:previewFullImage="true" accept="image" width="100px" height="100px"></u-upload>
						<commonLookImage v-else :imageArr="engineeringList[index].fileListImg" width="80px" height="80px" style="margin-bottom: 40rpx;"></commonLookImage>
				</view>
			</view>
		</template>
		<view style="height: 30rpx;background-color: #f5f7fb;"></view>
		<view v-if="showButton">
			<view @click="addItem"
				style="display: flex; align-items: center; justify-content: center; height: 96upx; background: #fff; border-radius: 4upx; margin: 0 32upx;">
				<u-icon name="plus" size="16" color="#2F80ED"></u-icon>
				<view style="font-weight: bold;color: #2F80ED;margin-left: 10rpx;">添加工程項</view>
			</view>
		</view>
		<view style="height: 30rpx;background-color: #f5f7fb;"></view>
		<view class="textarea_box">
			<view style="margin-bottom: 20rpx;">備注</view>
			<view class="form-item-description">
				<u-textarea :adjustPosition="false" :disabled="!showButton" v-model="formData.description" placeholder="請輸入内容" @blur="inputBlur" confirmType='done'></u-textarea>
				<record v-if="showButton" class="form-item-icon form-item-icon-voice" @setText="description"></record>
				<image v-if="showButton" mode="scaleToFill" class="form-item-icon form-item-icon-clear" src="/static/image/login/del1.png"
					@click="formData.description=''"></image>
			</view>
		</view>
		<flow-info :workOrderLogList="workOrderLogs"></flow-info>
		<view class="footer-button" v-if="showButton">
			<view class="button-placeholder"></view>
			<view class="button-group">
				<button @click="clickSubmit" :loading="isLoading" class="button-primary">提交</button>
			</view>
		</view>
	</view>
</template>


<script>
	import diseaseInfoVue from "./components/diseaseInfo.vue"
	import flowInfo from "./components/flowInfo.vue"
	import { hkRepairTask_save, hkRepairTask_get, hkRepairTask_getDetails, hkProjectItemsConfig_getNodeTree } from "@/api/HongKong/hkAttendanceSheet.js";
	import { handleFormatDate, compareDate } from "@/utils/date.js";
	import { uploadFile} from '@/utils/request'
	import { getPicture, deleteImg,doc_deleteAttachs } from '@/api/doc.js'
	import mixins from '@/utils/mixins.js'
	import {getToken} from '@/utils/auth.js'
	import { urlTobase64, uploadImageFromBase64} from '@/utils/imageOperation.js'
	import { imgFun } from "@/utils/common.js";
	export default {
		name: 'diseaseRepair',
		mixins:[mixins],
		data() {
			return {
				engineeringList: [{
					code: '',
					coding: '',
					name: '',
					projectItem: '',
					require:true,
					children: [],
					fileListImg: [], //视频照片 //图片
					docId: '', //图片id  后续接口要用
				}],
				isLoading: false,
				workOrderLogs: [],
				diseaseFormInfo: {},
				formData:{
					description:''
				},
				updateDiseaseId:undefined,
				showButton:true,
				isRequest:false,
				isRereport:false
			}
		},
		components: {
			diseaseInfoVue,
			flowInfo
		},
		mounted() {
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.on('sendFormInfo', async item => {
					console.log(item.data, '数据')
					this.diseaseFormInfo = item.data
					if(item.data.docId) {
						this.$set(this.diseaseFormInfo, 'imageList', await this.getItemImage(item.data.docId) || [])
					}else {
						this.$set(this.diseaseFormInfo, 'imageList', [])
					}
				})

				this.$forceUpdate()
				this.eventChannel = eventChannel
				
			

		},
		async onLoad(op) {
			if(op && op.id) {
				console.log(op, '0000',op.taskStateName)
				this.isRereport = true // 重新上报进来
				if(op.taskStateName === 'false') {
					this.showButton = false
				}
				let imgList = []
				if(op.docId) {
					imgList = await this.getItemImage(op.docId)
				}
				let result =  await this.getRecordDetail(op.id)
				this.updateDiseaseId = result.id
				console.log(result,'result')
				this.diseaseFormInfo = {...result.diseaseOrder, imageList:imgList, pmName:op.pmName, orderType:op.orderType, planRepairDiseaseId:result.hkPlanRepairDiseaseId}
				console.log(this.diseaseFormInfo,'--')
				this.workOrderLogs = result.workOrderLogs
				this.formData.description = result.remark
				if(this.$refs && this.$refs.diseaseInfoVueRef) {
					this.$refs.diseaseInfoVueRef.fillForm.constructionStartDate = this.getDate2(result.repairStartDate)
					this.$refs.diseaseInfoVueRef.fillForm.constructionEndDate = this.getDate2(result.repairEndDate)
					this.$refs.diseaseInfoVueRef.fillForm.repairState = result.repairState
				}
				// this.engineeringList = result.hkRepairProjectItems
				// 数据回显
				let resultTreeData = await this.getTableData()
				if(this.diseaseFormInfo.orderType === 'WO') {
					this.engineeringList = result.hkRepairProjectItems.map(it => {
						let children = []
						if(!it.hkProjectItemsAttributesList) {
							let tempChild = resultTreeData.find(item => item.id == it.hkProjectItemsConfigId)
							if(tempChild) {
								children = tempChild.children ? tempChild.children : []
							}
							console.log(tempChild, '哈哈哈')
						}
						if(it.hkProjectItemsAttributesList && it.hkProjectItemsAttributesList.length) {
							for (let i = 0, j = 0; i < it.hkProjectItemsAttributesList.length; i++){
								if (!children[j]) {
									children[j] = []
								}
								children[j].push({
									coding:it.hkProjectItemsAttributesList[i].attributes,
									value:it.hkProjectItemsAttributesList[i].value,
									parentId:it.hkProjectItemsAttributesList[i].hkProjectItemsConfigId,
								})
								if(!((i + 1) %  3)) {
									j++
								}
							}
						}

						if(it.hkProjectItemsConfigName.split(":")[0] == 'J') {
							return {
								coding:it.hkProjectItemsConfigName.split(":")[0] || '',
								projectItem:it.hkProjectItemsConfigName.split(":")[1] || '',
								value:it.hkProjectItemsAttributesList && it.hkProjectItemsAttributesList[0].value ? it.hkProjectItemsAttributesList[0].value : '',
								docId:it.repairImgDocId || '',
								id:it.hkProjectItemsConfigId,
								children:children
							}
						}
						return {
							coding:it.hkProjectItemsConfigName.split(":")[0] || '',
							projectItem:it.hkProjectItemsConfigName.split(":")[1] || '',
							id:it.hkProjectItemsConfigId,
							docId:it.repairImgDocId || '',
							children:children,
							code:it.hkProjectItemsConfigName.split(":")[0] === 'A' ? 'Scaffolding' : it.hkProjectItemsConfigName.split(":")[0] === 'C' ? 'Defect Size' : '',
						}
					})
					for(let item of this.engineeringList) {
						this.$set(item, 'fileListImg', item.docId ? await this.getItemImage(item.docId) : [])
					}
				}
				if(this.diseaseFormInfo.orderType === 'EO') {
					this.engineeringList = []
					if(result.hkRepairProjectItems && result.hkRepairProjectItems.length) {
						for(let item of result.hkRepairProjectItems) {
							this.engineeringList.push({
								value:item.hkProjectItemsConfigName,
								id:item.hkProjectItemsConfigId,
								docId:item.repairImgDocId || '',
								// fileListImg: item.repairImgDocId ? await this.getItemImage(item.repairImgDocId) : []
							})
						}
					}

					for(let it of this.engineeringList) {
						this.$set(it, 'fileListImg', it.docId ? await this.getItemImage(it.docId) : [])
					}
				}
				for(let it of this.engineeringList) {
					if(it.fileListImg.length) {
						it.sourceImgIds = JSON.parse(JSON.stringify(it.fileListImg))
					}else {
						it.sourceImgIds = []
					}
				}
				this.$forceUpdate()
				console.debug(this.engineeringList, '=11这样？竟然==')
				for(let item of this.engineeringList) {
					if(item.coding === 'D') {
						let arr = ['Dia', 'pcs', 'total length']
						let unitArr = ['mm', '', 'm']
						item.children = new Array(3).fill(0).map((it, index)=> item.children[index] || 
										new Array(3).fill(0).map((i, idx) => {
											return {
												coding:arr[idx],
												value:'',
												parentId:item.id,
												projectItem:unitArr[idx]
											}
										}))
					}
					
				}
			}
		},
		methods: {
			getRecordDetail(id) {
				return new Promise(resolve => {
					hkRepairTask_getDetails({id, projectId:uni.getStorageSync('isOwner')}).then(async res => {
						if(res.success) {
							resolve(res.result)
						}else {
							resolve({})
						}
					})
				})
				
			},
			getTableData() {
				return new Promise(resolve => {
					hkProjectItemsConfig_getNodeTree({projectId:uni.getStorageSync('isOwner')}).then(res => {
						if(res.success) {
							const treeData = res.result || []
							if(treeData.length) {
								for(let item1 of treeData) {
									item1.val = false
									item1.fileListImg = []
									if(item1.children && item1.children.length) {
										for(let item2 of item1.children) {
											for(let item3 of item2) {
												item3.value = ''
											}
										}
									}
								}
							}
							resolve(treeData)
						}else {
							resolve([])
						}
					})
				})

			},

			async getItemImage(docId) {
				return await new Promise((resolve, reject) => {
					getPicture({
						docId
					}).then(res => {
						resolve(res.result.map(it => ({
							id:it.id,
							url:this.$config.IMG_FILE_URL + it.fileName
						})));
					}).catch(err => reject(err))
				})
			},
			async afterRead(event, index) {
				let tempImgList = []
				for (let item in event.file) {
					event.file[item].url = await imgFun(event.file[item])
					event.file[item].thumb = await imgFun(event.file[item])
					this.engineeringList[index].fileListImg.push({
						...event.file[item],
						status: 'uploading',
						message: '上傳中'
					})
				}
				let fileList = [...this.engineeringList[index].fileListImg]
				for (let item of fileList) {
					if (!item.status) continue
					let formData = {}
					//通过index判断 避免图片id一直是同一个
					if (this.engineeringList[index].docId) {
						formData.docId = this.engineeringList[index].docId
					}
					const uploadImg = {
						url: "rest/doc/uploadDoc",
						formData,
						filePath: item.url
					}
					let data = await uploadFile(uploadImg)
					let res = JSON.parse(data)
					if (!res.success) return
					this.engineeringList[index].docId = res.result.id
					this.$set(this.engineeringList[index], 'fileListImg', await this.getItemImage(this.engineeringList[index].docId))
					this.engineeringList[index].updateIds = this.engineeringList[index].fileListImg.map(i => i.id) || []
				}
				this.$forceUpdate()
			},
			 deletePic(event, index) {
				this.$nextTick(async () => {
					if (event.file.id > 0) {
						const delres = await deleteImg({id: event.file.id})
						console.log(delres, '删除图片')
						if(delres.success) {
							// this.engineeringList[index].docId = ''
						}
					}
					this.engineeringList[index][`fileList${event.name}`].splice(event.index, 1)
				})
			},
			inputBlur(e) {
				this.cursor = e.detail.cursor
			},
			description(text) {
				let index = this.cursor || 0
				let str = this.formData.description || ""
				this.cursor += text.length
				text = str.slice(0, index) + text + str.slice(index);
				this.$set(this.formData, "description", text)
			},
			clickSubmit() {
				let repairStartDate = ''
				let repairEndDate = ''
				let repairState = undefined
				if(this.$refs && this.$refs.diseaseInfoVueRef) {
					repairStartDate = this.$refs.diseaseInfoVueRef.fillForm.constructionStartDate
					repairEndDate = this.$refs.diseaseInfoVueRef.fillForm.constructionEndDate
					repairState = this.$refs.diseaseInfoVueRef.fillForm.repairState
				}				
				if (!compareDate(repairEndDate, repairStartDate)) {
					uni.showToast({
						title: "結束時間不可早於開始時間！",
						icon: "none"
					});
					return;
				}
				if (!repairState) {
					uni.showToast({
						title: "請選擇維修狀態！",
						icon: "none"
					});
					return;
				}
				if (this.engineeringList.length === 0) {
					uni.showToast({
						title: "工程量必填！",
						icon: "none"
					});
					return;
				}
				// 组装WO数据格式
				let assembleArray = []
				console.log(this.engineeringList, '数组')
				// return
				if(this.diseaseFormInfo.orderType === 'WO') {
				  for (const item of this.engineeringList) {
					  if(!item.projectItem) return this.$message(`請選擇工作項！`)
					  // debugger
					// if (!item.val) {
					//   continue
					// }
					if (item.projectItem === 'Others' && !item.value)  return this.$message(`${item.coding}項 未填完整！`)
					if (item.children.length === 1) {
					  for (const item1 of item.children) {
						for (const item2 of item1) {
						  if (!item2.value.trim()) {
							return this.$message(`${item.coding}項 未填完整！`)
						  }
						}
					  }
					}else if (item.children.length) {
						// debugger
					  let tempIndex = 0
					  let result = false
					  for (const item1 of item.children) {
						tempIndex = 0
						for (const item2 of item1) {
						  if (item2.value.trim()) {
							tempIndex++
						  }
						}
						if (tempIndex !== 0 && tempIndex !== item1.length) {
						  result = true
						  break
						}
					  }
					  if (result) {
						return this.$message(`${item.coding}項 未填完整！`)
					  }
					}
					if (!item.fileListImg || !item.fileListImg.length) {
					  return this.$message(`${item.coding}項 維修照片未上傳！`)
					}
				  }
					
					assembleArray = this.engineeringList.map(item => {
						// if (!item.val) {
						//   return null
						// }
						if (item.projectItem === 'Others') {
						  return {
							hkProjectItemsAttributesList:[
								{
									hkProjectItemsConfigId: item.id,
									value: item.value,
									attributes:item.projectItem
								}
							],
							value: item.value,
							hkProjectItemsConfigId: item.id,
							repairImgDocId: item.docId,
							hkProjectItemsConfigName: `${item.coding}:${item.projectItem}`,
						  }
						}
						let hkProjectItemsAttributesList = []
						for (const item1 of item.children) {
						  for (const item2 of item1) {
							if (item2) {
							  hkProjectItemsAttributesList.push({ value: item2.value, hkProjectItemsConfigId: item.id, attributes: item2.coding })
							}
						  }
						}
						hkProjectItemsAttributesList = hkProjectItemsAttributesList.filter(item1 => item1.value)
						return {
						  hkProjectItemsConfigId: item.id,
						  repairImgDocId: item.docId,
						  hkProjectItemsAttributesList: hkProjectItemsAttributesList.length ? hkProjectItemsAttributesList : undefined,
						  hkProjectItemsConfigName: `${item.coding}:${item.projectItem}`,
						}
					  })
				}else if(this.diseaseFormInfo.orderType === 'EO') {
					for(let item of this.engineeringList) {
						if(!item.value) return this.$message(`工程項未填完整！`)
						if(!item.fileListImg || !item.fileListImg.length) return this.$message(`維修照片未上傳！`)
					}
					assembleArray = this.engineeringList.map(it => ({
							hkProjectItemsConfigName: it.value || undefined, //工程项配置名称【】
							repairImgDocId: it.docId ? it.docId : undefined, //维修图片【】
							// outputValue: undefined, //产值【】
							// orderType:this.diseaseFormInfo.orderType,
							// fileListImg:it.fileListImg || []
					}))
				}
				
				
				console.log(assembleArray, '组装的数据')
				if(this.diseaseFormInfo.orderType === 'WO') {
					const bool = this.hasDuplicateProperty(assembleArray, 'hkProjectItemsConfigId')
					if(bool) return this.$message('存在重複的工程項！')
				}
				const resq = {
					id: this.updateDiseaseId,
					projectId:uni.getStorageSync('isOwner'),
					hkPlanRepairDiseaseId: this.diseaseFormInfo.planRepairDiseaseId ? this.diseaseFormInfo.planRepairDiseaseId : '', //维修计划id
					repairStartDate: repairStartDate, //维修开始时间
					repairEndDate: repairEndDate, //维修结束时间
					repairState: repairState, //维修状态
					remark: this.formData.description, //备注
					hkRepairProjectItems: assembleArray //维修工程项
				}
				console.debug(resq, '入参')

				// return
				if(this.isLoading) return
				this.isLoading = true
				hkRepairTask_save(resq).then(resp => {
					console.log(resp)
					if(resp.success) {
						this.isLoading = false
						this.isRequest = true
						this.$message(resp)
						uni.showToast({
							title:resp.message,
							icon:'none',
							duration:1600,
						})
						setTimeout(() => {
							let pages = getCurrentPages()
							if(!this.isRereport) {
								// 2. 上一页面实例
								// 注意是length长度，所以要想得到上一页面的实例需要 -2
								// 若要返回上上页面的实例就 -3，以此类推
								let prevPage = pages[pages.length - 3]
								prevPage.$vm.getBackState(true)
								uni.navigateBack({
									delta: 2 // 返回的页面数
								})
							}else {
								// 2. 上一页面实例
								// 注意是length长度，所以要想得到上一页面的实例需要 -2
								// 若要返回上上页面的实例就 -3，以此类推
								let prevPage = pages[pages.length - 2]
								prevPage.$vm.getBackState(true)
								uni.navigateBack()
							}
								
						},1800)
					}
				}).catch(e => {
					console.log(e)
					this.isLoading = false
					this.isRequest = true
				})
			},
			hasDuplicateProperty(arr, property) {
			  const values = [];
			  return arr.some((item, index) => {
			    if (values.includes(item[property])) {
			      return true;
			    }
			    values.push(item[property]);
			    return false;
			  });
			},
			goWoItem(idx) {
				if(!this.showButton) return
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/hongKong/select/select-woItem?index=${idx}`,
					events: {
						getItemInfo: (data) => {
							console.log(data, 'children')
							this.$set(this.engineeringList, data.index, data.data)
						}
					},
				})
			},
			addItem() {
				this.engineeringList.push({
					code: '',
					coding: '',
					name: '',
					projectItem: '',
					require: true,
					children: [],
					fileListImg: [], //视频照片 //图片
					docId: '', //图片id  后续接口要用
				})
			},
			deleteItem(index) {
				this.engineeringList.splice(index, 1);
			},
			getDifference(arr1, arr2) {
				return arr1.concat(arr2).filter((v, i, arr) => {
					return arr.indexOf(v) === arr.lastIndexOf(v)
				})
			},
			
		},
		async beforeDestroy() {
			if(!this.isRequest) {
				for(let item of this.engineeringList) {
					// console.debug(item)
					// 新加图片后没有点击操作按钮直接退出 需要删除新加的id
					if(item.updateIds && item.updateIds.length) {
						let ids = item.sourceImgIds && item.sourceImgIds.map(i => i.id)
						let needDelIds = this.getDifference(ids, item.updateIds)
						await doc_deleteAttachs(needDelIds)
					}
					let result = this.getArrDifSameValue(item.fileListImg, item.sourceImgIds || [])
					// console.error(result)
					if(result.length) {
						for(let it of result) {
							let data = await uploadFile({
								url: "rest/doc/uploadDoc",
								formData:{docId:item.docId},
								filePath:it.url
							})
						}
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.label-txt {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 100rpx;
		background: #F5F7FA;
		padding: 0 50rpx;

		.left {
			font-weight: 600;
			font-size: 36rpx;
			color: #22204E;
		}
		.left::before {
			content: '*';
			color: red;
		}

		.right {
			font-weight: 800;
			font-size: 32rpx;
			color: #FF6A6A;
		}
	}

	.form-item {
		height: 100upx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin: 0 30upx;
		border-bottom: 1px solid #e2e5ed;

		// &:last-of-type {
		// 	border-bottom: none;
		// }

		.label {
			color: #445469;
			line-height: 44upx;
			flex-shrink: 0;
		}


		.form-content {
			color: #22204e;
			display: flex;
			align-items: center;
		}

		.form-text {
			line-height: 58upx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			max-width: 302upx;
		}

		.form-text.none {
			opacity: .7;
			font-size: 30rpx;
		}

		.u-icon {
			margin-left: 20upx;
		}

		.uicon-close-circle-fill {
			margin-left: 32upx;
		}

	}
	.label-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin: 20rpx 40rpx;
		border-bottom: 1px solid #e2e5ed;
		padding-bottom: 20rpx;
		.title-txt {
			font-weight: 500;
			font-size: 30rpx;
			color: #22204E;
		}
	}
	.label-tips {
		padding: 20rpx 40rpx;
	}
	.label-tips::before {
		content: '*';
		color: red;
	}
	.input-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 22rpx 32rpx;
	}



	.textarea_box {
		padding-top: 20rpx;
		padding-left: 32rpx;

		.form-item-description {
			width: 95%;
			position: relative;
			margin-bottom: 40rpx;

			.form-item-icon {
				width: 48rpx;
				height: 48rpx;
			}

			.form-item-icon-voice {
				position: absolute;
				top: 10rpx;
				right: 16rpx;
				z-index: 3;
			}

			.form-item-icon-clear {
				position: absolute;
				right: 16rpx;
				bottom: 10rpx;
				z-index: 2;
			}
		}

		/deep/.u-textarea {
			padding-right: 65rpx;
		}
	}

	.m40 {
		margin: 0 40rpx;
	}
	.picture_box_1 {
		padding-left: 32rpx;
		padding-bottom: 20rpx;
	
		.txt {
			padding-top: 20rpx;
			font-weight: 500;
			font-size: 32rpx;
			color: #445469;
			margin-bottom: 20rpx;
		}
	}

</style>